package com.noble.glamour.ui.agora.util;


import android.widget.Chronometer;

import com.noble.glamour.R;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.custom.CountDownTextView;
import com.noble.glamour.module.logic.baseui.custom.CountUpTextView;
import com.noble.glamour.module.logic.baseui.custom.CountUpTimer;
import com.noble.glamour.module.util.CountDownTimer;
import com.noble.glamour.ui.agora.model.AgoraConstant;
import com.noble.glamour.ui.agora.model.EngineConfig;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;

import java.util.ArrayList;
import java.util.List;

/**
 * 音视频： 各种通信计时管理类
 * <p>
 * Created by Su on 2017/6/30.
 */
public class RtcTimerUtil {
    private volatile static RtcTimerUtil mInstance;
    private List timer = new ArrayList<>();  // 维护计时Timer

    private RtcTimerUtil() {
        if (timer == null) timer = new ArrayList();
    }

    public static RtcTimerUtil getInstance() {
        if (mInstance == null) {
            synchronized (RtcTimerUtil.class) {
                if (mInstance == null) {
                    mInstance = new RtcTimerUtil();
                }
            }
        }
        return mInstance;
    }

    /**
     * 注册计时控件
     */
    public <T> void addTimer(T model) {
        if (timer == null) timer = new ArrayList();
        timer.add(model);
    }

    /**
     * 反注册
     */
    public <T> void removeTimer(T model) {
        if (timer != null)
            timer.remove(model);
    }

    /**
     * 释放所有注册计时控件
     */
    public void releaseAll() {
        if (timer == null || timer.size() <= 0) return;

        for (int i = 0; i < timer.size(); i++) {
            Object obj = timer.get(i);

            // 计时
            if (obj instanceof CountDownTextView) {
                ((CountDownTextView) obj).cancel();
            } else if (obj instanceof CountUpTextView) {
                ((CountUpTextView) obj).cancel();
            } else if (obj instanceof Chronometer) {
                ((Chronometer) obj).stop();
            }
        }
        timer.clear();
        timer = null;
    }

    private EngineConfig config() {
        return ModuleMgr.getRtcEnginMgr().getEngineConfig();
    }

    // ================================== 邀请计时 ==================================
    /**
     * 邀请计时
     */
    private CountUpTimer mInviteTimer;

    public void startStatisInvTime() {
        if (mInviteTimer != null) {
            return;  // 处于计时状态
        }

        int countUpInterval = 1000;
        mInviteTimer = new CountUpTimer(0, countUpInterval) {
            @Override
            public void onTick(long millisPass) {
                config().mInviteTime = millisPass;
                if (millisPass / 1000 == AgoraConstant.CHAT_TIME_AUTO_HUANGUP_GROUP ||
                        millisPass / 1000 == AgoraConstant.CHAT_TIME_AUTO_HUANGUP_SINGLE)
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Timer_Msg, AgoraConstant.TIMER_INVITE);
            }

            @Override
            public void onDisplay(long displayMillis) {
            }

            @Override
            public void onFinish(long millisTotal) {
            }
        };
        mInviteTimer.start();
    }

    public void stopStatisInvTime() {
        if (mInviteTimer != null)
            mInviteTimer.cancel();
        mInviteTimer = null;
    }

    // ================================== 通信计时 ==================================
    /**
     * 通信计时
     */
    private CountUpTimer mUpTimer;

    public void startStatisChatTime() {
        App.activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mUpTimer != null) {
                    mUpTimer.cancel();
                } else {
                    int countUpInterval = 1000;
                    mUpTimer = new CountUpTimer(0, countUpInterval) {
                        @Override
                        public void onTick(long millisPass) {
                            config().mTimespan = millisPass / 1000;
                            config().millisPass = millisPass;
                            if (millisPass / 1000 == AgoraConstant.CHAT_UPDATE_VIDEO_FIRST) {
                                MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Timer_Msg, AgoraConstant.TIMER_CHATING);
                            }
                        }

                        @Override
                        public void onDisplay(long displayMillis) {
                        }

                        @Override
                        public void onFinish(long millisTotal) {
                        }
                    };
                }
                mUpTimer.start();
            }
        });
    }

    public void stopStatisChatTime() {
        if (mUpTimer != null)
            mUpTimer.cancel();
        mUpTimer = null;
    }

    // ================================== 余额倒计时 ==================================
    private CountDownTimer mDownTimer;

    public void startStatisTipsTime(long mCountDownTime) {
        if (mDownTimer != null) {
            mDownTimer.cancel();
            mDownTimer = null;
        }

        int countDownInterval = 1000;
        mDownTimer = new CountDownTimer(mCountDownTime, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                long totalSec = millisUntilFinished / 1000 + (millisUntilFinished % (1000 * 60)) / 1000;
                config().millisLeft = totalSec;
                if (totalSec == AgoraConstant.CHAT_COST_PROMPT) {
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Timer_Msg, AgoraConstant.TIMER_LAST_TIPS);
                }
            }

            @Override
            public void onFinish() {
                config().reason = "余额不足，通讯关闭，调挂断接口";
                MsgMgr.getInstance().sendMsg(MsgType.MT_Rtc_Chat_Count_Finish_Msg, null);
                PToast.showShort(App.activity.getString(R.string.chat_pay_deficiency));
                stopStatisTipsTime();
                RtcJointChannel.getInstance().stopChat();
            }
        };
        mDownTimer.start();
    }

    public void stopStatisTipsTime() {
        if (mDownTimer != null)
            mDownTimer.cancel();
        mDownTimer = null;
    }

    // ================== 工具类 =====================

    /**
     * @param cmt Chronometer控件
     * @return 小时+分钟+秒数  的所有秒数
     */
    public long getChronometerSeconds(Chronometer cmt) {
        if (cmt == null) return 0;
        long totalss = 0;
        String string = cmt.getText().toString();
        if (string.length() == 7) {
            String[] split = string.split(":");
            String string2 = split[0];
            int hour = Integer.parseInt(string2);
            int Hours = hour * 3600;
            String string3 = split[1];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[2]);
            totalss = Hours + Mins + SS;
            return totalss;
        } else if (string.length() == 5) {
            String[] split = string.split(":");
            String string3 = split[0];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[1]);
            totalss = Mins + SS;
            return totalss;
        }
        return totalss;
    }
}
